package com.shujia.share;


/*
有一个线程, 其中的部分资源共享, 部分资源不共享
 */
public class ShareDemo3 extends Thread {

    // 共享的资源
    private NumberCount numberCount;

    // 不需要共享
    private int num;
    private Person person;


    public ShareDemo3(String name, NumberCount numberCount,
                      int num, Person person) {
        super(name);// 设置线程名称
        this.numberCount = numberCount;
        this.num = num;
        this.person = person;
    }

    public static void main(String[] args) {
        // 创建共享资源
        NumberCount count = new NumberCount();

        Person p1 = new Person();
        p1.age = 30;
        Person p2 = new Person();
        p2.age = 40;

        ShareDemo3 t1 = new ShareDemo3("线程1", count, 10, p1);
        ShareDemo3 t2 = new ShareDemo3("线程2", count, 20, p1);

        t1.start();
        t2.start();

        // join 让主线程等待子线程执行完毕再继续执行
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(count.getCount());

        System.out.println("t1:" + t1.num);
        System.out.println("t2:" + t2.num);

        System.out.println(p1.age);
        System.out.println(p2.age);

    }


    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(getName() + ":" + numberCount.getCount());
            numberCount.incr();
            num++;

            person.age++;

        }
    }
}
